import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text,RichText} from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './activitydetails.scss'

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
    	content:{},//活动详情
    	pics:[],//活动详情图片
    	userList:[],//报名用户信息列表
      isload:0,//判断页面是否加载完成
      ischange:false,
      contentzs:'',
      projectId:"",
      introduction:"",
      consumerGuide:"",
      ispyqfx:0,
      pmwidth:0,
      ewm:""
    }
  }
  config = {
    navigationBarTitleText: '加载中'
  }

  componentWillMount () {
    let projectId = this.$router.preload.activityId
    // console.log(projectId+'////projectId1111')
  	this.huidiao(projectId)
  	var dateinfo = Taro.getStorageSync('dateinfo');
  	var str=projectId+","+dateinfo.qid;
  	CommonJs.getFootPrint('COME',2,str);
  	var _this=this;
  	Taro.getSystemInfo({
		  success: res => 
		  _this.setState({
        pmwidth: res.screenWidth
      })
		})
  	if(dateinfo.qid&&projectId){
  		if(dateinfo.userid){
  			this.getShareEwm(dateinfo.qid,projectId,dateinfo.userid)
  		}
  		else{
  			this.getShareEwm(dateinfo.qid,projectId,0)
  		}
  	}
  }

  componentDidMount () { }

  componentWillUnmount () {
  	var dateinfo = Taro.getStorageSync('dateinfo');
  	var str=this.state.projectId+","+dateinfo.qid;
  	CommonJs.getFootPrint('GO',2,str);
  }

  componentDidShow () {
    //支付完成返回重新刷新
    // console.log(JSON.stringify(this.$scope.data))
    let data = this.$scope.data
    let ischange = data.ischange
    // console.log(ischange)
    if (ischange) {
      let projectId = this.$router.preload.activityId
      // console.log(projectId+'////projectId2222')
      this.userinfo(projectId)
      this.getuserns(projectId)
      this.setState({
        ischange: false
      })
    }
  }

  componentDidHide () { }
	
  onShareAppMessage(res){
    let title = '"'+this.state.content.name+'"，点击进入，和我一起参加活动吧'
    var dateinfo = Taro.getStorageSync('dateinfo');
    if(dateinfo.userid){
    	var uid=dateinfo.userid;
    }
    else{
    	var uid=0;
    }
    let path = '/pages/activity/activity?scene='+Taro.getStorageSync('dateinfo').qid+'aa'+this.$router.preload.activityId+'aa'+uid
    let imageUrl = this.state.content.logo
    return CommonJs.onShareAppMessage(title, path, imageUrl)
  }
  getShareEwm(qid,projectid,userid){
  	/*获取分享的二维码*/
  	var _this=this;
  	var url="/clusterlog/getWxQrCode?clusterId="+qid+"&activityId="+projectid+"&userId="+userid;
  	CommonJs.ajaxRequest(url,'','GET',function(res){
  		var ewmsrc=res.content;
  		ewmsrc=CommonJs.geturl()+"/upload"+ewmsrc.split("/upload")[1]
	     if(res.code!=300) {
	      	_this.setState({
		        ewm:ewmsrc,
		      })
	     }  
	      else {
	        Taro.showToast({
	          title:res.msg,
	          icon: 'none',
	          duration: 2000
	        })
	      }
	  })
  }
  opendetails(url,id){
  	var _this=this;
  	CommonJs.ajaxRequest('/user/getUser','','GET',function(res){
	     if (res.code!=300) {
	      	 _this.$preload('activityId',id)
    			 CommonJs.openTo(url)
	      } 
	      else {
	        Taro.showToast({
	          title:res.msg,
	          icon: 'none',
	          duration: 2000
	        })
	      }
	    },'noloading')
   
  }

  huidiao(projectId){
    this.getdata(projectId)
    this.userinfo(projectId)
    this.getuserns(projectId)
  }
  
  open(url){
  	CommonJs.open(url);
  }
  getdata(projectId){
  	//活动详情
    var _this=this
    var date = {
    	projectId:projectId
    }
    var url='/verify/papi/v1.9/project/'+projectId
    CommonJs.ajaxRequest(url,'','GET',function(res){
    	// console.log(JSON.stringify(res)+'6666666666')
      // _this.state.content = res;
      res=res.data;
      Taro.setNavigationBarTitle({title:res.name+"详情"})
      var pic = res.pic
      var piclist = []
    	if(pic){
        if(pic.indexOf(',') == -1){
            piclist.push(pic)
        }else{
            var pic = res.pic.split(',')
            for(var i=0; i<pic.length; i++){
                piclist.push(pic[i])
            }
        }
		  }
    	var consumerGuide=res.projectDescription.consumerGuide.replace(/<img/gi,'<img class="kdimg"').replace(/<table/gi, '<table class="kdtab"').replace(/<td/gi, '<td class="kdtabtd"')
    	var pic=res.projectDescription.pic;
    	if(pic.indexOf(',')>=0){
    		var arr=pic.split(",");
    		var str="";
    		for(var i=0;i<arr.length;i++){
    			str=str+'<img class="kdimg" src="'+arr[i]+'">'
    		}
    		
    	}
    	else{
    		var str='<img class="kdimg" src="'+pic+'">'
    	}
    	var introduction=res.projectDescription.introduction.replace(/<img/gi,'<img class="kdimg"').replace(/<table/gi, '<table class="kdtab"').replace(/<td/gi, '<td class="kdtabtd"')
      _this.setState({
        content: res,
        pics: piclist,
        isload: 1,
        projectId:projectId,
        consumerGuide:consumerGuide+str,
        introduction:introduction
      })
       
    },'wfw')
  }
  userinfo(projectId){
  	//获取报名用户信息列表
  	var _this=this;
    var date = {
    	projectId:projectId,//_this.$router.preload.activityId
    	pageSize:10000
    }
    var url='/verify/papi/v1.9/consumption-order/actualAuantityUse?shopId.equals='+projectId
    CommonJs.ajaxRequest(url,'','GET',function(res){
        // console.log(JSON.stringify(res)+'6666666666777777777777')
        _this.setState({
          userList: res.data
        })
    },'wfw')
  }
  look(index){
  	var list=this.state.userList;
  	this.$preload('pagename',list[index].userId);
    CommonJs.openTo("/pages/persinfo/persinfo");
  }
  getuserns(projectId){
    //统计活动（套餐）当天报名人数
    var _this=this
    var date = {
      projectId:projectId
    }
    var url='/verify/papi/v1.9/consumption-order/auantityCount/'+projectId
    CommonJs.ajaxRequest(url,'','GET',function(res){
        // console.log(JSON.stringify(res)+'6666666666777777777777')
        _this.setState({
          contentzs: res.data
        })
    },'wfw')
  }
  certificates(){
    let date = {
      status: 1,
      pageSize: 100,
      projectId:this.$router.preload.activityId
    }
    var url='/verify/papi/v1.9/consumption-order/consumptionPay?verifyStatus.equals=UNVERIFIED&size=1000&status.equals=SUCCESSFUL&projectId.equals='+this.$router.preload.activityId;
    CommonJs.ajaxRequest(url,'','GET',function(res){
        let result = res.data.list
	      let content = ''
	      let resultLen = result.length
	      if (resultLen == 0) {
	        content = '你还没有报名参加活动哟！'
	      } else {
	        for(var i = 0; i < resultLen; i++){
	          content += result[i].project.name+'（'+result[i].verifyCode+'）'
	        }
	      }
	      Taro.showModal({
	        title: '活动凭证码',
	        content: content,
	        showCancel: false
	      })
    },'wfw')
  }
  closeshare(){
  	this.setState({
		  ispyqfx:0
    })
  }
  pyqshare(){
  	Taro.showToast({
	    title:'正在加载数据...',
	    icon: 'none',
	    duration:1000
	  });
  	
  	let ctx = Taro.createCanvasContext('cardCanvas')
    
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, 0, 600, 1000);
    
    
    ctx.setFontSize(16)
    ctx.setFillStyle('black')
    var tit=this.state.content.name;
    var tith=0;
    if(tit.length>17){
    	ctx.fillText(tit.substring(0,17),20,30);
    	ctx.fillText(tit.substring(17,tit.length),20,50)
    	tith=60
    }
    else{
    	ctx.fillText(tit,20,30);
    	tith=40
    }
    
    ctx.setFontSize(14)
    ctx.setFillStyle('#999')
    var time="活动时间："+CommonJs.FormatDate(this.state.content.startAt,2)+"至"+CommonJs.FormatDate(this.state.content.finishAt,2)
    ctx.fillText(time,20,tith+20)
    tith=tith+20+20
    
    ctx.setFontSize(14)
    ctx.setFillStyle('#333')
    var address=this.state.content.activityAddress;
    var addressarr=[];
    if(address.length>18){
    	addressarr.push(address.substring(0,18))
    	addressarr.push(address.substring(18,address.length))
    	
    }
    else{
    	addressarr.push(address)
    }
    for(var i=0;i<addressarr.length;i++){
    	ctx.fillText(addressarr[i],20,tith+(i+1)*20)
    }
    tith=tith+addressarr.length*20
    ctx.setFontSize(14)
    ctx.setFillStyle('#999')
    var ptext="长按扫码了解活动详情";
    ctx.fillText(ptext,20,tith+80)
    var n=parseInt(this.state.pmwidth)*0.8-40;
    
    var logo=this.state.content.logo;
    logo=CommonJs.geturl()+"/upload"+logo.split("/upload")[1]
    var _this=this;
    var ewmsrc=this.state.ewm
    if(!ewmsrc){
    	Taro.showToast({
	      title:"小程序二维码获取错误，请重试",
	      icon: 'none',
	      duration: 2000
	    })
    	return false;
    }
    Taro.getImageInfo({
        src:ewmsrc,
	      success: function (res) {
	      	ctx.drawImage(res.path, 170, tith+20, 100, 100)
	      	Taro.getImageInfo({
			        src:logo,
				      success: function (ret) {
				      	ctx.drawImage(ret.path, 20, tith+120+20,n, ret.height*(n/ret.width))
				      	ctx.restore()
								ctx.draw()
								_this.setState({
								  ispyqfx: 1
						    })
				      }
					})
	      }
		})
    
  }
  saveimg(){
  	let res = Taro.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 600,
      height:1000,
      canvasId: 'cardCanvas',
      fileType: 'png',
      success:function(ret){
      	Taro.saveImageToPhotosAlbum({
		      filePath: ret.tempFilePath,
		      success:function(red){
		      	Taro.showModal({
			        title: '图片保存成功',
			        content: '图片成功保存到相册了，快去发朋友圈吧~',
			        showCancel: false,
			        confirmText: '确认'
			      })
		      },
		      fail:function(){
		      	Taro.showModal({
			        title: '图片保存失败',
			        content: '请重新尝试!',
			        showCancel: false,
			        confirmText: '确认'
			      })
		      }
		    })
      },
      fail:function(){
      	Taro.showModal({
	        title: '图片保存失败',
	        content: '请重新尝试!',
	        showCancel: false,
	        confirmText: '确认'
	      })
      }
   })
  }
  render () {
  	const content=this.state.content;
    const startAt = this.state.content.startAt
    const finishAt = this.state.content.finishAt
    //原来的返回
    // <View className='qun-back' onClick={this.opendetails.bind(this,'/pages/activity/activity','')}><Image className='qun-backimg' src={backwmall}></Image></View>
    return (
    	<View style={this.state.isload==1?'display:block':'display:none'} className={ispyqfx==1?'page nopage':'page'}>
				
	      <View className='qun-banner qun-xaqnzg'>
	      
	       <View className='qun-xq'>
	       	<Image className='qun-xqimg' mode='widthFix' src={content.logo}></Image>
	       	<View className='qun-xqmc'>
            <Text className='qun-xqtites'>{content.name}</Text>
            <Button openType='share' className='qun-fnxn buttons'>
              <Image className='qun-fnxnimg' mode='scaleToFill' src='https://minichat.g2ma.com/kedouimg/40.png'></Image>
              <Text className='qun-fxwn'>好友邀请</Text>
            </Button>
            <Button className='qun-fnxn buttons' onClick={this.pyqshare.bind(this)}>
              <Image className='qun-fnxnimg' mode='scaleToFill' src='https://minichat.g2ma.com/kedouimg/myorder7.png'></Image>
              <Text className='qun-fxwn'>朋友圈邀请</Text>
            </Button>
          </View>
          
	       	<View className='qun-xqinfo'>
	  				<View className='qun-dizi'>
	  					<Image className='ban-xqdz' src='https://minichat.g2ma.com/kedouimg/huod5.png'></Image>
	  					<Text decode='true' className='qun-xqdz'>{content.shopName.shopName}</Text>
	  				</View>
	  			</View>
	  			<View className='qun-xqinfo'>
	  				<View className='qun-dizi'>
	  					<Image className='ban-xqdz' src='https://minichat.g2ma.com/kedouimg/huod4.png'></Image>
	  					<Text decode='true' className='qun-xqdz'>￥{content.basePrice/100}</Text>
	  				</View>
	  			</View>
	  			<View className='qun-xqinfo'>
	  				<View className='qun-dizi'>
	  					<Image className='ban-xqdz' src='https://minichat.g2ma.com/kedouimg/huod1.png'></Image>
	  					<Text decode='true' className='qun-xqdz'>{content.cityName}{content.areaName}{content.districtName}{content.activityAddress}</Text>
	  				</View>
	  			</View>
	  			<View className='qun-xqinfo'>
	  				<View className='qun-dizi'>
	  					<Image className='ban-xqdz' src='https://minichat.g2ma.com/kedouimg/huod3.png'></Image>
	  					<Text decode='true' className='qun-xqdz'>{CommonJs.FormatDate(startAt,2)}至{CommonJs.FormatDate(finishAt,2)}&nbsp;&nbsp;&nbsp;具体时间: {content.concreteTime?content.concreteTime:'全天'}</Text>
	  				</View>
	  			</View>
	       </View>
	       
	       <View className='qun-bomn'>
	       	<View className='qun-bomes'>
	       		<Text className='qun-ybomn'>已报名 ({this.state.contentzs}人)</Text>
	       		<Text className='qun-qbomn' decode='true' onClick={this.certificates.bind(this)}>活动凭证码 &gt;</Text>
	       	</View>
	       	<View className='qun-bomnry'>

	       		{this.state.userList.map((item, index) => (
	       		<View className='qun-bomnli' onClick={this.look.bind(this,index)}>
	       			<Image className='qun-bmtoxn' src={item.imageUrl}></Image>
	       			<Text className='qun-bomnmc'>{item.nickName?item.nickName:item.name}</Text>
              <View className='qun-sulny'>x{item.num}</View>
	       		</View>
	       		))}

	       	</View>
	       </View>
	       
	       <View className='qun-hodoxag'>
	       	<View className='qun-hodosomn'>活动详情</View>
	       	<View className='qun-hodosum'>
	       		<View className='qun-hodosunm'>
	       			<View className='qun-hodotxt txt1'>{content.category.name+' ● '+content.name}</View>

	       			{this.state.pics.map((item, index) => (
	       			<Image className='qun-hodoxaqn txt2' mode='widthFix' src={item}  key={index}></Image>
	       			))}

	       			<RichText  className='qun-hodotxt txt2' nodes={this.state.consumerGuide} />
	       		</View>
	       	</View>
	       </View>
	       
	       <View className='qun-hodoxag'>
	       	<View className='qun-hodosomn'>报名须知</View>
	       	<View className='qun-hodosum'>
	       		<View className='qun-hodosunm'>
	       			<RichText  className='qun-hodotxt txt1' nodes={this.state.introduction} />
	       		</View>
	       	</View>
	       </View>
	       {content.projectStatus == 2 ?
          <View className='qun-zhfu1'>活动已结束</View>
          :
          <View className='qun-zhfu'>
            <View className='qun-fuyn'>
              <Text className='qun-bmfy'>报名费用: </Text>
              <Text className='qun-bmoney'>￥{content.basePrice/100}</Text>
            </View>
            <View className='qun-ljbomn' onClick={this.opendetails.bind(this,'/pages/activitybm/activitybm',this.$router.preload.activityId)}>立即报名</View>
          </View>
         }
	       
	      </View>
	      <View className='pyqshare' style={this.state.ispyqfx==1?'':'display:none;'}>
		       <Canvas className="card-canvas" canvasId="cardCanvas" ></Canvas>
		       <View className='share-btn'>
		       		<Text className='btn01' onClick={this.saveimg}>保存到相册后分享</Text>
              <Text className='btn02' onClick={this.closeshare}>关闭</Text>
		       </View>
	      </View>
      </View>
    )
  }
}